var loginPageConfig = {
    loginType: 0, //登陆类型
    returnUrl: '../main/main1.html'
}



//获取登陆cookie
function GetLoginCookie() {
    return $.cookie('userInfo');
}

//反渲染cookie到页面
function renderLoginCookie() {
    var userInfo = $.cookie('userInfo');
    if (userInfo == null) return false;
    userInfo = JSON.parse(userInfo);

    for (key in userInfo) {

        if (key != 'slideChk') {
            var el = $("#" + key);
            var t = $(el).attr("type");
            if (t == 'checkbox') {
                //$("#rememberUserInfo").attr('checked', userInfo.rememberUserInfo);
                $("#" + key).attr('checked', userInfo[key]);
            } else {
                $("#" + key).val(userInfo[key]);
            }
            $("#" + key).val(userInfo[key]);
        }

    }

}

//保存登陆信息
function SaveLoginCookie(userInfo) {
    var rememberUserInfo = $('#rememberUserInfo').is(':checked');
    userInfo["rememberUserInfo"] = rememberUserInfo;
    $.cookie('userInfo', JSON.stringify(userInfo), {
        expires: 7
    });
}

//清除登陆信息
function ClearLoginCookie() {
    $.removeCookie('userInfo');
}

//是否函数
function isFunction(obj) {
    return Object.prototype.toString.call(obj) === '[object Function]'
}

// inlineBlock 兼容safari
function inlineBlockHack() {
    $('.inline-block-container').contents().filter(function() {
        return this.nodeType === 3;
    }).remove();
}

//验证失败回的焦点去红框
function loginInputNoValidFocusBind() {
    $(".login-input").focus(function() {
        $(this).parent('.input-item').removeClass('input-item-unvalid')
    });
}

//通用定义方法
var DataCheckRule = {
    NOT_EMPTY: {
        reg: function(val) {
            if (val == "" || val == undefined || val == null) {
                return false;
            }
            return true;
        },
        errMsg: '不能为空'
    }
};

//通用验证
function dataCheck(data, ruleObj, callBackFun) {
    callBackFun = callBackFun || function(key, ruleObj, regItem) {
        toastr.options = {
            "closeButton": true,
            "debug": false
        };
        toastr.error(ruleObj[key].name + regItem.errMsg);
        $("[name=" + key + "]").parent('.input-item').addClass('input-item-unvalid')
    }
    for (key in data) {
        if (ruleObj[key] != undefined && data.hasOwnProperty(key) && (typeof data[key] == "string" || typeof data[key] == "number")) {
            if (ruleObj.hasOwnProperty(key)) {
                var curRuleArr = ruleObj[key]['ruleArr'];
                for (i = 0; i < curRuleArr.length; i++) {
                    var regItem = curRuleArr[i];
                    var reg = regItem.reg;
                    if (isFunction(reg)) {
                        var itemChkResult = reg(data[key]);
                        if (!itemChkResult) {
                            callBackFun && callBackFun(key, ruleObj, regItem);
                            return false;
                        }
                    } else {
                        var regItem = curRuleArr[i];
                        var re = new RegExp(regItem.reg);
                        itemChkResult = re.test(data[key])
                        if (!itemChkResult) {
                            callBackFun && callBackFun(key, ruleObj, regItem);
                            return false;
                        }
                    }
                }
            }
        }
    }
    return true;
}


//配置验证规则
var rules = {
    'loginName': {
        name: '登陆名',
        ruleArr: [
            DataCheckRule.NOT_EMPTY, {
                reg: /^[a-zA-Z0-9_-]{4,16}$/,
                errMsg: '要求长度4~16位,字母，数字，下划线，减号'
            }
        ]
    },
    pwd: {
        name: '密码',
        ruleArr: [
            DataCheckRule.NOT_EMPTY, {
                reg: /^[A-Za-z0-9]{6,16}$/,
                errMsg: '要求6-16字母数字组成'
            }
        ]
    },
    slideChk: {
        name: '',
        ruleArr: [{
                reg: function(val) {
                    if (val == 1) return true;
                    return false;
                },
                errMsg: "请将滑块拖至最右侧"
            }

        ]
    },
    phoneNum: {
        name: "手机号",
        ruleArr: [{
                reg: /^1(3|4|5|7|8)\d{9}$/,
                errMsg: "要求11位有效手机号"
            }

        ]
    },
    msgCode: {
        name: "短息验证码",
        ruleArr: [
            DataCheckRule.NOT_EMPTY
        ]
    }

};

$(function() {


    $("#mainwrap").backstretch([
        "../static/images/login/bg1.png",
        "../static/images/login/bg2.png",
        "../static/images/login/bg3.png",
        "../static/images/login/bg4.png",
        "../static/images/login/bg5.png"
    ], {
        duration: 1000,
        fade: 750
    });

    loginInputNoValidFocusBind();

    renderLoginCookie();

    inlineBlockHack();

    //滑动验证码
    window.mySwiper = new Swiper('.swiper-container', {
        effect: 'slide', //slide
        pagination: '.login-title',
        paginationClickable: true,
        paginationBulletRender: function(swiper, index, className) {
            var config = {
                '0': {
                    titleName: '帐号密码登陆'
                },
                '1': {
                    titleName: '手机验证码登陆'
                },
                '2': {
                    titleName: '二维码扫描登陆'
                }
            };
            if (index == 2) {
                return '<div class="qr-login-title ' + className + '">' + config['' + index].titleName + '</div>';
            }
            return '<div class="' + className + '">' + config['' + index].titleName + '</div>';
        },
        onSlideChangeEnd: function(swiper) {
            loginPageConfig.loginType = swiper.activeIndex;

        }
    });
    //屏蔽滑动
    window.mySwiper.disableTouchControl()

    $("#qrcodeSildeBtn").click(function() {
        if (mySwiper.activeIndex == 2) {
            $(this).addClass('fa-qrcode').removeClass('fa-desktop');
            $(".login-title .swiper-pagination-bullet:not('.qr-login-title')").show();
            mySwiper.slideTo(1);
        } else {
            $(this).removeClass('fa-qrcode').addClass('fa-desktop');
            mySwiper.slideTo(2);
            $(".login-title .swiper-pagination-bullet:not('.qr-login-title')").hide();
        }
    });


    //验证码发送及倒计时  开始
    var sendMsgCodeCallFun = function() {

        //先验证手机号

        var curSubmitData = {
            phoneNum: $("#phoneNum").val()
        }
        var curRules = {
            phoneNum: rules.phoneNum
        }

        var chkResult = dataCheck(curSubmitData, curRules);
        if (!chkResult) return false;

        toastr.success("您的验证码已发送到18627726186,请注意查收", "温馨提示");
        var i = 6
        $(".sendmsgcode").unbind('click');
        timeInterval = setInterval(function() {
            i = i - 1;
            $(".sendmsgcode").text(i + "秒");
            if (i == 0) {
                clearInterval(timeInterval);
                $(".sendmsgcode").text("重新发送");
                $(".sendmsgcode").bind('click', sendMsgCodeCallFun);
            }
        }, 1000)
    };
    $(".sendmsgcode").bind('click', sendMsgCodeCallFun);
    //验证码发送及倒计时  结束

    //滑动验证  开始
    $("#dragslider").slider({
        width: 310, // width
        height: 40, // height
        sliderBg: "#E9EAEC", // 滑块背景颜色
        color: "#555", // 文字颜色
        fontSize: 14, // 文字大小
        bgColor: "#E0FEF0", // 背景颜色
        textMsg: "按住滑块，拖动到最右边", // 提示文字
        successMsg: "验证通过", // 验证成功提示文字
        successColor: "#1ABC68", // 滑块验证成功提示文字颜色
        time: 400, // 返回时间
        callback: function(result) { // 回调函数，true(成功),false(失败)
            //验证成功改为1
            if (result) {
                $("#slideChk").val(1);
            }
        }
    });
    //滑动验证  结束

    //登陆开始
    $(".login-btn").click(function() {

        //获取数据
        var submitData = {};
        if (loginPageConfig.loginType == 0) {
            submitData = {
                loginName: $("#loginName").val() || "",
                //pwd: $("#pwd").val() || "",
                slideChk: $("#slideChk").val() || ""
            };
        } else if (loginPageConfig.loginType == 1) {
            submitData = {
                phoneNum: $("#phoneNum").val() || "",
                msgCode: $("#msgCode").val() || "",
            };
        }


        //开始验证
        var chkResult = dataCheck(submitData, rules);
        if (!chkResult) return false;

        submitData.loginType = loginPageConfig.loginType;

        //$.ajax();  //发送异步  自行实现吧

        //成功后回调
        var rememberUserInfo = $('#rememberUserInfo').is(':checked');
        if (rememberUserInfo) {
            SaveLoginCookie(submitData);
        } else {
            ClearLoginCookie();
        }

        toastr.success("登陆成功,正在跳转...");
        window.location.href = loginPageConfig.returnUrl;

    });
    //登陆结束

    // 登陆框架显示效果 开始
    function testAnim(x) {
        $('#loginwrap').removeClass().addClass(x + ' animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
            $(this).removeClass();
        });
    };
    testAnim("bounceInDown");
    // 登陆框架显示效果 结束

    //监听窗口事件 开始
    $(window).bind("load resize", function() {
        var outerWidth = $(window).width();
        var outerHeight = $(window).height();

        $("#mainwrap").css({
            height: outerHeight - 150 + 'px'
        });

        $("#loginwrap").css({
            'margin-top': ((outerHeight - 150) / 2) - 225 + 'px'
        });

    });
    //监听窗口事件 结束


})